package com.demo.web;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.demo.entity.MeUser;
import com.demo.server.LoginServer;
import com.demo.support.Interceptor.JHandleInter;
import com.demo.web.base.BaseModel;
import com.jweb.annotaion.JAutowired;
import com.jweb.annotaion.JController;
import com.jweb.annotaion.JParam;
import com.jweb.core.handle.Controller;
import com.jweb.core.handle.Handle;
import com.jweb.util.FormatUtil;
import com.jweb.util.WebUtil;

/**
 * 登录
 * 
 * @author Yuan
 *
 */
@JController("/login")
public class LoginController extends Controller {
	private Logger log = LoggerFactory.getLogger(Handle.class);
	@JAutowired
	public LoginServer server;

	public void init() {
		// log.info("该方法定义后，每次请求都会执行，也可以把该方法删掉");
	}

	/**
	 * 执行登录
	 */
	public void ajaxLoginAction(@JParam("loginName") String login_name, @JParam("password") String password, HttpServletRequest request) {
		BaseModel bs = new BaseModel();
		int error = FormatUtil.toInt(WebUtil.getSessionAttribute(request, "loginErr"));// 登录错误次数
		MeUser t = server.loginCheck(login_name, password);
		if (t != null) {
			WebUtil.setSessionAttribute(request, "loginErr", null);
			WebUtil.setSessionAttribute(request, JHandleInter.USER, t);
			JHandleInter.userSessionIdMap.put(t.getUserId(), WebUtil.getSessionId(request));
			log.info("登录成功：" + JSON.toJSONString(t));
		} else {
			WebUtil.setSessionAttribute(request, "loginErr", ++error);
			bs.setRetCode(BaseModel.ERROR);
			bs.setRetMsg("登录失败:帐号或密码错误");
			bs.setObj(error);
		}
		toWriterJSON(bs);
	}

	/**
	 * 执行退出
	 */
	public void exit(HttpServletRequest request) {
		BaseModel bs = new BaseModel();
		WebUtil.setSessionAttribute(request, JHandleInter.USER, null);
		toWriterJSON(bs);
	}
}
